<?php
namespace app\task\controller;
use app\task\logic\WechatLogic;

/**
 * 微信控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/10/12
 * Time: 17:14
 */
class Wechat extends Base{

    public function __construct(){
        parent::__construct();
        $this->w_logic = new WechatLogic();
    }

    /**
     * 获取access_token
     * @return \think\response\Json
     */
    public function deal_access_token(){
        $appid = \think\facade\Config::get('xcx.xcx_appid');
        $appsecret = \think\facade\Config::get('xcx.xcx_appsecret');

        $tools = new \app\common\controller\Tools();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;

        $maps = [];
        $maps[] = ['key','=','access_token'];
        $conf_info = $this->w_logic->get_conf_info($maps);

        $access_token_arr = json_decode($conf_info['access_token'],true);
        $r_json = '';
        if(empty($access_token_arr)){
            $r_json = $tools->GetuseCurl($url);
        }else{
            $dead_time = $access_token_arr['dead_time'];
            $now_time = time();
            if($now_time >= $dead_time){
                $r_json = $tools->GetuseCurl($url);
            }
        }

        if(empty($r_json)){
            return json($this->w_logic->get_response(1,'access_token未过期'));
        }

        $r_arr = json_decode($r_json,true);
        if(array_key_exists('errcode',$r_arr)){
            return json($this->w_logic->get_response(0,'获取access_token失败'));
        }

        //超时时间
        $dead_time = time() + $r_arr['expires_in'] - 600;
        $r_arr['dead_time'] = $dead_time;

        $maps = [];
        $maps[] = ['key','=','access_token'];

        $c_data = [];
        $c_data['value'] = json_encode($r_arr);
        $r = model('conf')->force()->save($c_data,$maps);
        return json($this->w_logic->get_response(1,'获取access_token成功'));
    }
}